<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="创建时间" prop="createTime">
        <!-- <el-date-picker clearable v-model="queryParams.createTime" is-range value-format="yyyy-MM-dd HH:mm:ss"
          placeholder="请选择创建时间">
        </el-date-picker> -->
        <el-date-picker v-model="timeRange" type="daterange" value-format="yyyy-MM-dd HH:mm:ss" range-separator="至"
          start-placeholder="开始日期" end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="人员姓名" prop="workerName">
        <el-input v-model="queryParams.workerName" placeholder="请输入人员姓名" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['jobs:intention:add']">新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['jobs:intention:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['jobs:intention:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['jobs:intention:export']" v-show="false">导出</el-button>
      </el-col> -->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="intentionList" @selection-change="handleSelectionChange">
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <el-table-column label="编号" align="center" prop="id" />
      <el-table-column label="人员姓名" align="center" prop="workerName" />
      <el-table-column label="性别" align="center" prop="sexCode">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_user_sex" :value="scope.row.sexCode" />
        </template>
      </el-table-column>
      <el-table-column label="联系方式" align="center" prop="workerPhone" />
      <el-table-column label="零工类型" align="center" prop="gigCode">
        <template slot-scope="scope">
          <span>{{ findLabelByValue(scope.row.gigCode)}}</span>
        </template>
      </el-table-column>
      <el-table-column label="期望薪酬" align="center" prop="expectedSalary" />

      <el-table-column label="结算方式" align="center" prop="settlementMethodCode">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.settlement_method" :value="scope.row.settlementMethodCode" />
        </template>
      </el-table-column>
      <el-table-column label="求职区域" align="center" prop="areaCode" />
      <el-table-column label="个人简介" align="center" prop="workerIntro">
        <template slot-scope="scope">
          <el-popover
            placement="top-start"
            width="200"
            trigger="hover"
            :content="scope.row.workerIntro"
          >
            <span class="ellipsis" slot="reference">{{ scope.row.workerIntro }}</span>
          </el-popover>
        </template>
      </el-table-column>

      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.status" />
        </template>
      </el-table-column>

      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>

      <el-table-column label="启用/停用" align="center" prop="status" width="180">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.status" active-value="0" inactive-value="1"
            @change="(value) => handleStatusChange(value, scope.row)">
          </el-switch>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['jobs:intention:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['jobs:intention:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改人才大厅对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" :inline="true" label-width="80px">

        <el-form-item label="姓名" prop="workerId">
          <el-select v-model="form.workerId" placeholder="请选择归属" style="width: 200px;" @change="workerChange">
            <el-option v-for="item in workerOptions" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="姓名" prop="workerName" v-show="false">
          <el-input v-model="form.workerName" placeholder="请选择用户" />
        </el-form-item>

        <!-- <el-form-item label="年龄" prop="workerAge">
          <el-input v-model="form.workerAge" placeholder="请输入用户年龄" />
        </el-form-item>

        <el-form-item label="性别" prop="sexCode">
          <el-select v-model="form.sexCode" placeholder="请选择性别" style="width: 200px;">
            <el-option v-for="dict in dict.type.sys_user_sex" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="联系方式" prop="workerPhone">
          <el-input v-model="form.workerPhone" placeholder="请输入用户联系方式" />
        </el-form-item> -->

        <el-form-item label="零工行业" prop="industry">
          <el-select v-model="form.industry" placeholder="请选择行业" style="width: 200px;" @change="workChange">
            <el-option v-for="item in workOptions" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="零工类型" prop="gigCode">
          <el-select v-model="form.gigCode" placeholder="请选择行业" style="width: 200px;">
            <el-option v-for="item in workTypeOptions" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="期望薪酬" prop="expectedSalary">
          <el-input v-model="form.expectedSalary" placeholder="请输入期望薪酬/元" />
        </el-form-item>

       

        <el-form-item label="求职区域" prop="address">
          <el-cascader
            v-model="form.address"
            placeholder="选择工作地区"
            :options="addressOptions"
            :props="{ label: 'name', value: 'id' }"
            style="width: 200px"
            @change="(value)=>addressChange(value)"
            filterable></el-cascader>
        </el-form-item>

        <el-form-item label="详细地址" prop="areaCode">
          <el-input v-model="form.areaCode" placeholder="请输入详情地址" />
        </el-form-item>

        <el-form-item label="结算方式" prop="settlementMethodCode">
          <el-select v-model="form.settlementMethodCode" placeholder="请选择结算方式" style="width: 200px;">
            <el-option v-for="item in dict.type.settlement_method" :key="item.value" :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="个人简介" prop="workerIntro">
          <el-input v-model="form.workerIntro" placeholder="请输入个人简介" type="textarea" style="width: 200px;" />
        </el-form-item>

        <el-form-item label="状态" prop="status" v-show="false">
          <el-radio-group v-model="form.status">
            <el-radio v-for="dict in dict.type.sys_normal_disable" :key="dict.value" :label="dict.value">{{ dict.label
              }}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { addIntention, changeStatus, delIntention, getIntention, listIntention, updateIntention } from "@/api/jobs/intention";
import { typeCascadeList } from "@/api/market/type";
import { findRegionTreeLevel3 } from "@/api/system/region";
import { workerOptions } from "@/api/user/info";
export default {
  name: "Intention",
  dicts: ['sys_normal_disable', 'settlement_method', 'job_area', 'sys_user_sex'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 人才大厅表格数据
      intentionList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        createTime: null,
        workerName: null,
        createTimeBegin: '',
        createTimeEnd: ''
      },
      timeRange: [],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        workerId: [
          { required: true, message: "姓名不能为空", trigger: "blur" }
        ],
        workerAge: [
          { required: true, message: "年龄不能为空", trigger: "blur" }
        ],
        sexCode: [
          { required: true, message: "性别不能为空", trigger: "blur" }
        ],
        workerPhone: [
          { required: true, message: "联系方式不能为空", trigger: "blur" }
        ],
        industry: [
          { required: true, message: "零工行业不能为空", trigger: "blur" }
        ],
        gigCode: [
          { required: true, message: "零工类型不能为空", trigger: "blur" }
        ],
        expectedSalary: [
          { required: true, message: "期望薪酬不能为空", trigger: "blur" }
        ],
      },
      // 岗位 数据
      workOptions: [],
      // 类型数据
      workTypeOptions: [],
      selectedWorkTypeValue: [],
      // 人员数据
      workerOptions: [],
      addressOptions: [],
    };
  },
  created() {
    this.getList();
    this.getTypeCascadeOptions();
    this.getWorkerOptions();
    this.getAddressOption();
  },
  methods: {

    // 获取公司/用户 下拉框
    getWorkerOptions() {
      workerOptions().then(response => {
        this.workerOptions = response.data;
      });
    },

        // 地区
    addressChange(value){
      this.form.regionProvince = value[0];
			this.form.regionCity = value[1];
			this.form.regionDistrict = value[2];
    },

    // 获取地区数据
    getAddressOption(){
      findRegionTreeLevel3().then((response)=>{
        this.addressOptions = response.data
        console.log('获取地区数据',response.data,this.addressOptions);
      })
    },

    // 修改状态
    handleStatusChange(value, row) {
      const data = {
        id: row.id,
        status: value
      }
      changeStatus(data).then(() => {
        this.getList();
      })
    },

    // 获取公司id 对应的label
    // getWorkerLabel(companyId) {
    //   const option = this.workerOptions.find(item => item.value === companyId.toString());
    //   return option ? option.label : '';
    // },
    // 
    workerChange(value) {
      const workerLabel = this.workerOptions.find(item => item.value === value).label;
      this.form.workerName = workerLabel;
    },


    // 获取岗位级联数据
    getTypeCascadeOptions() {
      typeCascadeList().then(response => {
        this.workOptions = response.data;
      });
    },

    // 行业
    workChange(value) {
      this.form.gigCode = "";
      this.form.gigCodeArr = [];
      const data = this.workOptions.find((item) => item.value === value).children;
      this.workTypeOptions = data
    },

    /** 查询人才大厅列表 */
    getList() {
      this.loading = true;
      listIntention(this.queryParams).then(response => {
        this.intentionList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        workerId: null,
        workerIntro: null,
        expectedSalary: null,
        settlementMethodCode: null,
        areaCode: null,
        createTime: null,
        updateTime: null,
        delFlag: null,
        gigCode: null,
        workerName: null,
        status: null,
        createTimeBegin: null,
        createTimeEnd: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.queryParams.createTimeBegin = this.timeRange ? this.timeRange[0] : null;
      this.queryParams.createTimeEnd = this.timeRange ? this.timeRange[1] : null;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.timeRange = null;
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      // this.form.workerId = 0;
      this.open = true;
      this.title = "添加";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getIntention(id).then(response => {
        const gigLabel = this.findParentValue(this.workOptions, response.data.gigCode);
        this.workChange(gigLabel);
        const address = [response.data.regionProvince,response.data.regionCity,response.data.regionDistrict]
        const data = {
          ...response.data,
          workerId: response.data.workerId.toString(),
          industry: gigLabel,
          gigCode: response.data.gigCode.toString(),
          address: address
        }
        this.form = data;
        this.open = true;
        this.title = "修改";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateIntention(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addIntention(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除人才大厅编号为"' + ids + '"的数据项？').then(function () {
        return delIntention(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('jobs/intention/export', {
        ...this.queryParams
      }, `intention_${new Date().getTime()}.xlsx`)
    },

    findParentValue(data, targetValue) {
      // 遍历每一项
      for (let item of data) {
        if (item.children) {
          // 遍历子项
          for (let child of item.children) {
            if (child.value === targetValue) {
              return item.value; // 返回父级的 value
            }
          }
        }
      }
      return null; // 如果没有找到，返回 null
    },



    // 入参1 为数组  入参2 为值  返回父级和子级label
    findLabelByValue(value) {
      const data = this.workOptions;
      for (let item of data) {
        if (item.children) {
          for (let child of item.children) {
            if (child.value === value) {
              return `${item.label}-${child.label}`; // 直接拼接并返回
            }
          }
        }
      }
      return null; // 如果没有找到对应的值，返回null
    }
  },
};
</script>

<style>
.ellipsis {
  display: inline-block;
  max-width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>
